from django import forms
from web.forms.boot_strap import BootStrap
from web import models
from django.core.exceptions import ValidationError
from web.forms.widgets import ColorRadioSelect

class ProjectModelForm(BootStrap,forms.ModelForm):

    def __init__(self, request,  *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.request = request

    bootstrap_class_exclude = ["color"]
    # desc = forms.CharField(widget=forms.Textarea())
    class Meta:
        model = models.Project
        fields = ["title", "color", "desc"]
        widgets = {
            "desc": forms.Textarea(),
            "color": ColorRadioSelect(attrs={
                "class": "color-radio"
            })
        }

    def clean_title(self):
        """项目校验"""
        title = self.cleaned_data.get("title")
        print(title)
        # 1.检查用户是否已经创建过此项目（项目名是否存在）
        exists = models.Project.objects.filter(title=title, creator=self.request.tracer.user).exists()
        # print(exists)
        if exists:
            raise ValidationError("项目名已存在")
        # 2. 当前用户是否还有额度进行创建项目
        # 最多创建N个项目，从价格策略中获取 self.request.tracer.price_policy.project_num


        # 现在已经创建多少个项目？
        count = models.Project.objects.filter(creator=self.request.tracer.user).count()
        # print(count)
        if count >= self.request.tracer.price_policy.project_num:
            raise ValidationError("项目个数超限，请购买套餐")

        return title



